package com.zxbit.uangstore.main;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.cloud.progressbar.ProgressButton;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.zxbit.uangstore.BuildConfig;
import com.zxbit.uangstore.CashLoanApplication;
import com.zxbit.uangstore.R;
import com.zxbit.uangstore.adapter.ProductAdapter;
import com.zxbit.uangstore.base.BaseActivity;
import com.zxbit.uangstore.business.DialogManager;
import com.zxbit.uangstore.business.RouterMap;
import com.zxbit.uangstore.cache.Acache;
import com.zxbit.uangstore.cache.UserInfo;
import com.zxbit.uangstore.constant.Constant;
import com.zxbit.uangstore.constant.SPKeys;
import com.zxbit.uangstore.domain.BlankResponse;
import com.zxbit.uangstore.domain.ProductItemData;
import com.zxbit.uangstore.domain.ProductResponse;
import com.zxbit.uangstore.domain.UpdateResponse;
import com.zxbit.uangstore.mvpview.MainMvpView;
import com.zxbit.uangstore.permission.IPermisson;
import com.zxbit.uangstore.permission.Permission;
import com.zxbit.uangstore.presenter.MainPresenter;
import com.zxbit.uangstore.utils.ApkUtils;
import com.zxbit.uangstore.utils.DebugLog;
import com.zxbit.uangstore.utils.NoDoubleClickUtils;
import com.zxbit.uangstore.utils.StringUtils;
import com.zxbit.uangstore.utils.ToastUtils;
import com.zxbit.uangstore.view.GrantPermissionDialog;
import com.zxbit.uangstore.view.UpdateVersionDialog;
import com.zxbit.uangstore.view.ViewUpSearch;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import crossoverone.statuslib.StatusUtil;

import static com.zxbit.uangstore.constant.Constant.PROPERTY_ROTATION;
import static com.zxbit.uangstore.constant.Constant.PROPERTY_TRANSLATION_X;

@RequiresApi(api = Build.VERSION_CODES.M)
@SuppressLint("CheckResult")
@Route(name = "首页", path = RouterMap.MAIN_ACTIVITY_PAGE)
public class MainActivity extends BaseActivity implements MainMvpView, ViewUpSearch.OnSearchListener,
        ProductAdapter.OnProductListener, IPermisson {

    @BindView(R.id.search_view)
    ViewUpSearch search;
    @BindView(R.id.login_header)
    ImageView loginHeader;
    @BindView(R.id.img_loan_header)
    ImageView img_loan_header;
    @BindView(R.id.btn_layout)
    LinearLayout btn_layout;
    @BindView(R.id.btn_cash_loan)
    TextView btnCashLoan; // 现金
    @BindView(R.id.btn_installment)
    TextView btnInstallment; // 分期
    @BindView(R.id.cash_loan_refresh_layout)
    SmartRefreshLayout cashLoanRefreshLayout;
    @BindView(R.id.recycler_cash_loan)
    RecyclerView cashLoanRecycler;

    private ProductAdapter productAdapter;
    private Permission permission;
    private GrantPermissionDialog grantPermissionDialog;
    private UpdateVersionDialog updateVersionDialog;

    private MainPresenter mainPresenter;
    private int mCurrentPage = 0; // 当前页page
    private int mIndex = 0; // 当前位置
    private boolean isDownloading;

    private int mLlSearchHeight; // 搜索框的高度(动画用)
    private int mScrollY;  //recyclerview 滑动的距离(动画用)
    private boolean isShow;  // 按钮布局是否显示(动画用)
    String filePath; // 8.0安装权限 文件路径
    ProgressButton btn_download;

    @Override
    protected void setSystemInvadeBlack() {
        StatusUtil.setUseStatusBarColor(this, Color.parseColor("#00000000"));
        // 第二个参数是是否沉浸,第三个参数是状态栏字体是否为黑色。
        StatusUtil.setSystemStatus(this, true, true);
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this, this);
        permission = new Permission(this, this);
        permission.requestAll();

        if (!BuildConfig.isRecord) {
            loginHeader.setVisibility(View.GONE);
        }
        search.setListener(this);
        btnCashLoan.setSelected(true);
        cashLoanRefreshLayout.setEnableRefresh(false);// 关闭下拉刷新
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        cashLoanRecycler.setLayoutManager(linearLayoutManager);
        cashLoanRecycler.setAdapter(getRecyclerAdapter());
        // 上拉加载
        cashLoanRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (NoDoubleClickUtils.isDoubleClick()) return;
                getProductList(false);
            }
        });

        // 监听RecyclerView滑动
        cashLoanRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (mLlSearchHeight == 0) {
                    mLlSearchHeight = img_loan_header.getHeight() - 40;
                }
                //记录滑动的距离
                mScrollY += dy;
                if (mScrollY > 0 && dy == 0) mScrollY = 0;

                if (dy > 0) {
                    if (!isShow && mScrollY > mLlSearchHeight) {
                        performAnimation(isShow);
                    }
                } else {
                    if (isShow && mScrollY < mLlSearchHeight) {
                        performAnimation(isShow);
                    }
                }
            }
        });
    }

    private void performAnimation(final boolean flag) {
        AnimatorSet animatorSet = new AnimatorSet();
        float[] rotationLeft = !flag ? new float[]{360f, 0f} : new float[]{0f, 360f};
        float[] left = !flag ? new float[]{0, -loginHeader.getLeft() - loginHeader.getWidth()}
                : new float[]{-loginHeader.getLeft() - loginHeader.getWidth(), 0};
        float[] right = !flag ? new float[]{0, search.getRight()}
                : new float[]{search.getRight(), 0};

        animatorSet.playTogether(
                ObjectAnimator.ofFloat(loginHeader, PROPERTY_ROTATION, rotationLeft).setDuration(500),
                ObjectAnimator.ofFloat(loginHeader, PROPERTY_TRANSLATION_X, left).setDuration(500),
                ObjectAnimator.ofFloat(search, PROPERTY_TRANSLATION_X, right).setDuration(500)
        );
        animatorSet.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                btn_layout.setVisibility(flag ? View.GONE : View.VISIBLE);
                isShow = !flag;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                animation.removeAllListeners();
            }
        });
        animatorSet.start();
    }

    @Override
    protected void onUIReady() {
        mainPresenter = new MainPresenter(this);

        mainPresenter.googlePlayUpdate();
        checkAppPermission();

        showLoadingView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getProductList(true);
    }

    private void checkAppPermission() {
        boolean grant = false;
        if (Acache.get(CashLoanApplication.getContext()).getAsObject(SPKeys.GRANT) != null) {
            grant = (boolean) Acache.get(CashLoanApplication.getContext()).getAsObject(SPKeys.GRANT);
        }

        if (!grant) {
//            permission = new Permission(MainActivity.this, this);
            grantPermissionDialog = new GrantPermissionDialog(MainActivity.this);
            grantPermissionDialog.show();
            grantPermissionDialog.setOnClickListener(new GrantPermissionDialog.GrantPermissionDialogCallBack() {
                @Override
                public void onConfirm() {
//                    permission.requestAll();
                    Acache.get(CashLoanApplication.getContext()).put(SPKeys.GRANT, true);
                    grantPermissionDialog.hide();
                }

                @Override
                public void onCancel() {
                    finish();
                }
            });
        }
    }

    @Override
    protected int getContentResId() {
        return R.layout.layout_of_main;
    }

    @Override
    protected int getResId() {
        return 0;
    }

    @Override
    public void onPermissonSuccess(int... result) {

    }

    public ProductAdapter getRecyclerAdapter() {
        if (productAdapter == null) {
            productAdapter = new ProductAdapter(this, this);
        }
        return productAdapter;
    }

    @OnClick({R.id.login_header, R.id.btn_cash_loan, R.id.btn_installment})
    public void onClick(View view) {
        if (NoDoubleClickUtils.isDoubleClick()) return;
        switch (view.getId()) {
            case R.id.login_header:
                if (!UserInfo.isLogin()) {
                    ARouter.getInstance().build(RouterMap.LOGIN_METNOD_PAGE).navigation();
                } else {
                    ARouter.getInstance().build(RouterMap.MINE_ACTIVITY_PAGE).navigation();
                }
                break;
            case R.id.btn_cash_loan:
                if (!btnCashLoan.isSelected()) {
                    mIndex = 0;
                    btnCashLoan.setSelected(true);
                    btnInstallment.setSelected(false);
                    getProductList(true);
                }
                break;
            case R.id.btn_installment:
                if (!btnInstallment.isSelected()) {
                    mIndex = 1;
                    btnInstallment.setSelected(true);
                    btnCashLoan.setSelected(false);
                    getProductList(true);
                }
                break;
        }
    }

    @Override
    public void onGetDataError(Throwable throwable) {
        dismissLoadingView();
    }

    private void getProductList(boolean isRefresh) {
        if (isRefresh) {
            mCurrentPage = 0;
            showLoadingView();
        }

        mCurrentPage++;
        mainPresenter.getProduct(mIndex, mCurrentPage, search.getText());
    }


    @Override
    public void onSearchClick() {
        getProductList(true);
    }

    @SuppressLint({"NewApi", "LocalSuppress"})
    @Override
    public void onHistoryClick(View btn, ProductItemData itemData, boolean isInstall) {
        if (BuildConfig.isRecord) {
            if (UserInfo.isLogin()) {
                if (!isDownloading) {
                    btn_download = (ProgressButton) btn;
                    mainPresenter.insertHistory(itemData, isInstall);
                } else {
                    ToastUtils.showShort(MainActivity.this, getStringResource(R.string.main_product_downloading));
                }
            } else {
                ARouter.getInstance().build(RouterMap.LOGIN_METNOD_PAGE).navigation();
            }
        } else {
            if (!isDownloading) {
                btn_download = (ProgressButton) btn;
                BlankResponse response = new BlankResponse();
                response.setStatus(Constant.HTTP_OK);
                onGetDataNext(response, isInstall, itemData);
            } else {
                ToastUtils.showShort(MainActivity.this, getStringResource(R.string.main_product_downloading));
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void setInstallPermission() {
        boolean haveInstallPermission = MainActivity.this.getPackageManager().canRequestPackageInstalls();
        if (!haveInstallPermission) {
            //权限没有打开则提示用户去手动打开
            toInstallPermissionSettingIntent();
        } else {
            if (!StringUtils.isEmpty(filePath)) {
                ApkUtils.install(MainActivity.this, filePath);
            }
            filePath = "";
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void toInstallPermissionSettingIntent() {
        Uri packageURI = Uri.parse("package:" + getPackageName());
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        startActivityForResult(intent, Constant.INSTALL_PERMISS_CODE);
        ToastUtils.showShort(MainActivity.this, getStringResource(R.string.get_permission_failure_hint));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == Constant.INSTALL_PERMISS_CODE) {
            if (!StringUtils.isEmpty(filePath)) {
                ApkUtils.install(MainActivity.this, filePath);
            }
            filePath = "";
        }
    }

    @Override
    public void onTabClick(String type) {
        if ("cashloan".equals(type)) {
            if (!btnCashLoan.isSelected()) {
                mIndex = 0;
                btnCashLoan.setSelected(true);
                btnInstallment.setSelected(false);
                getProductList(true);
            }
        } else {
            if (!btnInstallment.isSelected()) {
                mIndex = 1;
                btnInstallment.setSelected(true);
                btnCashLoan.setSelected(false);
                getProductList(true);
            }
        }
    }

    @Override
    public void onGetDataNext(ProductResponse productResponse) {
        dismissLoadingView();
        if (productResponse.getStatus() == Constant.HTTP_OK) {
            if (productResponse.hasData()) { // 有数据
                if (mCurrentPage == 1) {
                    getRecyclerAdapter().updateItemsAddHead(productResponse.getData());
                    if (productResponse.getData().size() >= Integer.valueOf(Constant.LIMIT)) {
                        cashLoanRefreshLayout.resetNoMoreData();//复原状态
                    } else {
                        cashLoanRefreshLayout.finishLoadmoreWithNoMoreData();
                    }
                    cashLoanRefreshLayout.setEnableLoadmore(productResponse.getData().size() >= Integer.valueOf(Constant.LIMIT));
                } else {
                    getRecyclerAdapter().addItems(productResponse.getData());
                }
            } else {
                mCurrentPage--;
                cashLoanRefreshLayout.finishLoadmoreWithNoMoreData();//显示全部加载完成，并不再触发加载更事件
                if (mCurrentPage == 0) {
                    getRecyclerAdapter().removeAllItemsSaveHead();
                }
            }

            cashLoanRefreshLayout.finishLoadmore();
        } else {
            ToastUtils.showShort(MainActivity.this, productResponse.getMessage());
        }
    }

    @Override
    public void onGetDataNext(final UpdateResponse updateResponse) {
        if (updateResponse.hasData()) {
            if (updateVersionDialog == null) {
                updateVersionDialog = new UpdateVersionDialog(this, R.style.normal_dialog);
            }
            updateVersionDialog.setContent(getStringResource(R.string.new_version_code) +
                    updateResponse.getData().getAppVersion() + "\n" + updateResponse.getData().getDesc());
            updateVersionDialog.setTitle(getStringResource(R.string.checkout_new_version));
            if (updateResponse.getData().isUpdate()) {
                updateVersionDialog.setCancelable(false);
            } else {
                updateVersionDialog.setCancelable(true);
            }

            updateVersionDialog.setNormalClickListener(new UpdateVersionDialog.NormalClickListener() {

                @SuppressLint("CheckResult")
                @Override
                public void onConfirmClick() {
                    ApkUtils.launchAppDetail(MainActivity.this, updateResponse.getData().getpName());
                }
            });
            DialogManager.getManager().showDialogStack(updateVersionDialog);
        }
    }

    @Override
    public void onGetDataNext(BlankResponse response, boolean isInstall, ProductItemData data) {
        if (response.getStatus() == Constant.HTTP_OK) {
            if ("1".equals(data.getAttr1())) {
                if (isInstall) {
                    ApkUtils.installOrOpen(MainActivity.this, isInstall, data.getPackageName());
                    return;
                }
                final String videoName = data.getApkName();
                final String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/miniDownLoad";
                FileDownloader.getImpl().create(data.getDownloadUrl())
                        .setPath(path + "/" + videoName, false)
                        .setCallbackProgressTimes(300)
                        .setMinIntervalUpdateSpeed(400)
                        .setListener(new FileDownloadListener() {
                            @Override
                            protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                                // 等待，已经进入下载队列
                                isDownloading = true;
                            }

                            @Override
                            protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                                // 下载进度回调
                                int percent = (int) ((double) soFarBytes / (double) totalBytes * 100);
                                btn_download.setText("("+percent+"%"+")");
                                btn_download.setProgress(percent);
                            }

                            @Override
                            protected void completed(BaseDownloadTask task) {
                                // 完成整个下载过程
                                btn_download.setText(getStringResource(R.string.main_product_open));
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                    filePath = path + "/" + videoName;
                                    setInstallPermission();
                                } else {
                                    ApkUtils.install(MainActivity.this, path + "/" + videoName);
                                }
                                isDownloading = false;
                            }

                            @Override
                            protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                                // 暂停下载
                            }

                            @Override
                            protected void error(BaseDownloadTask task, Throwable e) {
                                // 下载出现错误
                                isDownloading = false;
                            }

                            @Override
                            protected void warn(BaseDownloadTask task) {
                                // 在下载队列中(正在等待/正在下载)已经存在相同下载连接与相同存储路径的任务
                                isDownloading = false;
                            }
                        }).start();
            } else {
                ApkUtils.installOrOpen(MainActivity.this, isInstall, data.getPackageName());
            }
        } else {
            ToastUtils.showShort(MainActivity.this, response.getMessage());
        }
    }
}
